//
//  SearchViewController.m
//  HomeIn
//
//  Created by dllo on 15/11/10.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "SearchModel.h"
#import "SearchDetialViewController.h"
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>

@property(nonatomic,strong)UITableView *myTableView;
@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,retain)NSMutableArray *searchArray;

@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //视图将要出现的时候刷新
    [self.myTableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //导航栏左侧按钮
    UIImage *image = [UIImage imageNamed:@"iconfont-unie642.png"];
    //取消渲染
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(leftBarAction)];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0 * HEIGHTSCALE);
    //设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    self.myTableView.sectionHeaderHeight = 30 * HEIGHTSCALE;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 375 * WIDTHSCALE, 30 * HEIGHTSCALE)];
    SearchModel *model = [self.searchArray objectAtIndex:section];
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:model.name];
    [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.name rangeOfString:[self.searchController.searchBar text]]];
    label.attributedText = att;
    return label;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.searchArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        
        cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    SearchModel *model = [self.searchArray objectAtIndex:indexPath.section];
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:model.desc];
    [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.desc rangeOfString:[self.searchController.searchBar text]]];
    cell.att = att;
    cell.model = model;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchDetialViewController *DetailVc = [[SearchDetialViewController alloc]init];
    SearchModel *model = [self.searchArray objectAtIndex:indexPath.section];
    DetailVc.model = model;
    DetailVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:DetailVc animated:YES];
}

//让UITableView的section header view不悬停的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 30 * HEIGHTSCALE;
    if (scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y >= sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150 * HEIGHTSCALE;
    
}

// 网络搜索根据关键字转化为NSUTF8StringEncoding来搜索
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    NSString *str = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [BlockGetAFNYiBu GetAfnURLWithString:[NSString stringWithFormat:@"http://api.bohejiaju.com/v1/search/item?keyword=%@&limit=20&offset=0&sort=",str] resultBlock:^(id result) {
        
        self.searchArray = [NSMutableArray array];
        NSMutableDictionary *Dic = result;
        NSMutableDictionary *Dic1 = [Dic objectForKey:@"data"];
        NSMutableArray *array = [Dic1 objectForKey:@"items"];
        for (NSMutableDictionary *dic in array) {
            
            SearchModel *model = [[SearchModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            model.desc = [dic objectForKey:@"description"];
            [self.searchArray addObject:model];
        }
        
        [self.myTableView reloadData];
        
    } errorBlcok:^(NSError *error) {
        
        
    }];
}


//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

//键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.searchController.searchBar resignFirstResponder];
}

- (void)leftBarAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
